Click here to Skip to main content
15,901,666 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi everyone...
Can anyone please explain me , why and where we use "out" keyword and the significance of it. Thanks in advance
Posted

The out keyword just means that the parameter is passed by reference rather than by value. This basically means that the called method can change the value. Take a look at the MSDN page out(C#)[^] for examples and clearer explanation.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 20-Mar-12 16:45pm    
That's not all; you should have explained how it's different from "ref". (I voted 4.) I added proper explanation in my answer, please see.
--SA
In addition to what Wayne explains:

The keyword out also says that the parameter should change the value in the method implementation. The code sample below shows that constraint and explains essential difference between ref and out; both modes are by-reference:
C#
struct MyStructure { /*...*/ }

struct SomeType {
    void SomeMethod(ref MyStructure reference) { } //does nothing, but it will compile
    void SomeBadMethod(out MyStructure reference) { } //will not compile because out parameter is not assigned
    void FixedMethod(out MyStructure reference) {
        //...
        out = new MyStructure(/*...*/); //this will fix the above method, will compile
    }
}


[EDIT]

Also, a calling code is not required to initialize a variable used as out parameter (as it will be initialized as a result of the call).

—SA
 
Share this answer
 
v4
 
Share this answer
 
The out descriptor tells the intermediate language compiler to copy the actual variable storage location, not just the value at a storage location. Out parameters are often most useful for value types such as bool because there is no other easy way to return multiple values without allocating an array or object.

Even the variable passed as out parameter is similar to ref, but there are few implementation differences when you use it in C# .

Argument passed as ref must be initialized before it is passed to the method, where as in case of out its is not necessary, but after a call to the method as an out parameter the variable must be initialized. Also the out argument cannot be used until its value is set. This means that values cannot be passed in in an argument marked with out.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900